<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

use Zend\Http\PhpEnvironment\Request;

class MemberController extends \MLM\Model\Generic\Controller {

    
    public function indexAction() {
        $identity = $this->hasSession();

        if ($identity->member_type_id == 4)
            $this->layout('layout/admin');
        else
            $this->layout('layout/member');

        $storage = new \MLM\Model\Member\Storage($this->_db);


        //GET NEW MEMBER
        $newMembers = $storage->getNewMitra($identity->member_id, 10);

        /*
        while ($newMember->next()) {
                $res = $newMember->current();
                $memberName = $res['member_name'];
                $joinDate = $res['start_dtm'];
        }
         * 
         */


        //GET JUMLAH JARINGAN
        $numMembers = $storage->getNumMitra($identity->member_id);
        $numMember = 0;
        while ($numMembers->next()) {
                $res = $numMembers->current();
                $numMember = $res['total'];
        }


        //GET JUMLAH TRANSAKSI
        $trans = $storage->getNumTransaction($identity->member_code);
        $numTrans = 0;
        while ($trans->next()) {
                $res = $trans->current();
                $numTrans = $res['total'];
        }


        //GET TOTAL WD
        $transWD = $storage->getTotalWD($identity->member_code);
        $totalWD = 0;
        while ($transWD->next()) {
                $res = $transWD->current();
                $totalWD = $res['total'];
        }


        //GET PENDING WD
        $transWD = $storage->getTotalWD($identity->member_code, 'APPROVAL');
        $pendingWD = 0;
        while ($transWD->next()) {
                $res = $transWD->current();
                $pendingWD = $res['total'];
        }


        //GET LATEST WD
        $transWD = $storage->getTotalWD($identity->member_code, 'LATEST');
        $latestWD = 0;
        while ($transWD->next()) {
                $res = $transWD->current();
                $latestWD = $res['total'];
        }
   

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        //GET JUMLAH SALDO
        $balance = $accStorage->getTotalBalance($identity->member_code);

        $numBalance = 0;
        $numEarning = 0;
        $numBalanceTurnOver = 0;
        while ($balance->next()) {
                $res = $balance->current();
                $numBalance = $res['amount2'];
                $numBalanceTurnOver = $res['amount'];
                $numEarning = $res['amount'] + $res['amount_1'] + $res['amount_2'] + $res['amount_3'] + $res['amount_4'];
        }

        
        //Get Active Investment
        $activeInvest = 0;
        if ($identity->subs_end_dat != ""){

            $arrEndDate = explode(" ", $identity->subs_end_dat);       

            $date1 = strtotime("now");
            $date2 = strtotime($arrEndDate[0]);

            $secs = $date2 - $date1; // == <seconds between the two times>
            $days = $secs / 86400;

            $activeInvest = ($days > 0) ? $identity->subs_amount : 0;
        }

        $view = new ViewModel();
        $view->setVariable('newMembers', $newMembers);
        $view->setVariable('numMember', $numMember);
        $view->setVariable('numTrans', $numTrans);
        $view->setVariable('numBalance', $numBalance);
        $view->setVariable('numBalanceTurnOver', $numBalanceTurnOver);
        $view->setVariable('numEarning', $numEarning);
        $view->setVariable('activeInvest', $activeInvest);
        $view->setVariable('totalInvest', $identity->total_subs_amount);
        $view->setVariable('totalWD', $totalWD);
        $view->setVariable('pendingWD', $pendingWD);
        $view->setVariable('latestWD', $latestWD);
        $view->setVariable('memberID', $identity->member_code);
        $view->setVariable('memberName', $identity->member_name);
        $view->setVariable('startDtm', $identity->start_dtm);
        $view->setVariable('lastLogin', $identity->last_login);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Dashboard</li>";
        return $view;
    }

    public function profileAction() {
        $identity = $this->hasSession();

        $storage = new \MLM\Model\Member\Storage($this->_db);
        $storageContact = new \MLM\Model\Member\Contact\Storage($this->_db);
        $storageAcc = new \MLM\Model\Member\Account\Storage($this->_db);


        $memberId = $identity->member_id;

        $profile = $storage->getMemberDetail($memberId);
        $contact = $storageContact->getMemberContact($memberId);
        $family = $storageContact->getMemberContactFamily($memberId);
        $banks = $storageAcc->getAccountBank($memberId);

        $dataBank = array();
        while ($banks->next()) {
                $bank = $banks->current();
                $dataBank['account_id'] = $bank['account_id'];
                $dataBank['account_num'] = $bank['account_num'];
                $dataBank['account_name'] = $bank['account_name'];
                $dataBank['account_status'] = $bank['account_status'];
                $dataBank['bank_id'] = $bank['bank_id'];
                $dataBank['bank_name'] = $bank['bank_name'];
                $dataBank['bank_acc_no'] = $bank['bank_acc_no'];
                $dataBank['bank_acc_name'] = $bank['bank_acc_name'];
                $dataBank['bank_city_name'] = $bank['bank_city_name'];
        }
        
        $functModel = new \MLM\Model\Functions;
        
        $view = new ViewModel();
        $view->setVariable('functModel', $functModel);
        $view->setVariable('memberProfile', $profile);
        $view->setVariable('memberContact', $contact);
        $view->setVariable('memberFamily', $family);
        $view->setVariable('bank', $dataBank);
        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        $this->layout()->navMenu = "<li class='active'>Profile</li> <li class='active'>View Profile</li>";
        return $view;
    }
	
	public function passAction(){
		$identity = $this->hasSession();
        // seting layout 
        
        $this->layout('layout/member');
        $view = new ViewModel();
		
		return $view;
	}
	
    public function addAction() {
        $identity = $this->hasSession();
        // seting layout 
        
        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object 
        
        //$form = array();
        
        $getParams = $this->getRequest()->getQuery();
		if(isset($getParams['parent'])){
			$view->setVariable('parent', $getParams['parent']);
		}
        //print_r($identity);
        $data = array();
        
        $data['sponsorId'] = $identity->member_id;
        $data['sponsorCode'] = $identity->member_code;
        $data['sponsorName'] = $identity->member_name;
        
        $db = $this->_db;
        
        $conn = $db->getDriver()->getConnection();
        
        $storage = new \MLM\Model\Member\Storage($db);
        $member = new \MLM\Model\Member($storage);
       
        $uplines = $storage->listParent($identity->member_id);
		
		$up = array();
		while ($uplines->next()) {
			$upline = $uplines->current();
			array_push($up,$upline);
		}

        $view->setVariable('uplines', $up);
        $view->setVariable('data', $data);
        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);
            
            $data = array_merge($data,  get_object_vars($post));
            //print_r($data);
            $view->setVariable('data', $data);
            // assign data member
            $member->name = $post->name;
            $member->code = $post->code;
			$pin = $post->pin;
            $member->parentId = $post->parentId;
            $member->sponsorId = $post->sponsorId;
			$member->matrik1Id = $post->parentId;
            $member->typeId = 2;
			$member->statusId = 1;
            $member->startDtm = $storage->now();

            //validate parent
			
			$pstat = $member->validateParent($member->parentId);
			
			if($pstat['code'] == 'F'){
				$conn->rollback();
                $view->setVariable('msg', $pstat['msg']);
                return $view;
			
			}
			
			
			// get info SN 

            $sn = $member->validateSN($member->code);
            //print_r($stat);
            if ($sn['code'] == 'F') {
                $conn->rollback();
                $view->setVariable('msg', $sn['msg']);
                return $view;
            }
            
			if ($pin != $sn['pin']){
				$conn->rollback();
                $view->setVariable('msg', 'Pin tidak valid!!');
                return $view;
			}
			
            $member->pin = md5($sn['pin']);
            
            $memberId = $member->save();
            
            if(!$memberId){
                $conn->rollback();
                $view->setVariable('msg', 'Penambahan member Gagal');
                return $view;
            }
            $member->id = $memberId;
			
            /*
             * Account 
             */
            
            $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
            $acc = new \MLM\Model\Member\Account($accStorage);
            
            $acc->accNum = $member->code;
            $acc->accName = $member->name;
            $acc->memberId = $memberId;
			$acc->amount = 0;
			$acc->amount1 = 0;
			$acc->amount3 = 0;
			$acc->amount2 = 0;
            $acc->status = 'OK';
            
            
            $accId = $acc->save();
            
            if(!$accId){
                $conn->rollback();
                $view->setVariable('msg', 'Pembuatan account Gagal');
                return $view;
            }
            // contact data
            /*
             * insert contact
             * insert member_contact
             */
            
            
            $cStorage = new \MLM\Model\Contact\Storage($this->_db);
            $contact = new \MLM\Model\Contact($cStorage);
            
            $contact->name = $post->name;
            $contact->mobile = $post->mobile;
            
            $contactId = $contact->save();
            
            if(!$contactId){
                $conn->rollback();
                $view->setVariable('msg', 'Pembuatan kontak gagal');
                return $view;
            }
            
            $mcStorage = new \MLM\Model\Member\Contact\Storage($this->_db);
            $memberContact = new \MLM\Model\Member\Contact($mcStorage);
            
            $memberContact->memberId = $memberId;
            $memberContact->contactId = $contactId;
            $memberContact->typeId = 2;
            $memberContact->startDat = $mcStorage->now();
            
            $mcId = $memberContact->save();
            
            if(!$mcId){
                $conn->rollback();
                $view->setVariable('msg', 'Pembuatan kontak member gagal');
                return $view;
            
            }
            
			// update sn to acktive 
			
			$snstatus = $storage->updateSn($member->code,3);
			
			$req = $member->createRequest();
			if(!$req){
				$conn->rollback();
                $view->setVariable('msg', 'Request add member gagal');
                return $view;
			}
            $conn->commit();
            
            return $this->redirect()->toUrl('../network');
           
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return $view;
    }

    public function saveAction() {
        $this->layout('layout/member');

        $post = $this->getRequest()->getPost();

        $storage = new \MLM\Model\Member\Storage($this->_db);
        $member = new \MLM\Model\Member($storage);

        // assign data member
        $member->name = $post['name'];
        $member->code = $post['code'];
        $member->parentId = $post['parentId'];
        $member->sponsorId = $post['sponsorId'];
        $member->typeId = 2;
        $member->startDtm = $storage->now();

        // get info SN 

        $stat = $member->validateSN($member->code);



        // contact data

        $member->ktp = $post['ktp'];
        $member->mobile = $post['mobile'];

        $save = $member->save();
        if ($save) {
            return $this->redirect()->toUrl('../network');
        } else {
            $view = new ViewModel();

            $view->setVariables(array('post' => $post));

            return $view;
        }
    }


    public function jqgridAction() {
        $view = new ViewModel();
        $view->setTerminal(true);
        return $view;
    }


    public function addmemberAction(){
        $this->layout('layout/member');
        
        $identity = $this->hasSession();

        $view = new ViewModel();

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Member\Storage($db);
        $member = new \MLM\Model\Member($storage);
        $functModel = new \MLM\Model\Functions;

        $data = array();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);

            $data = array_merge($data,  get_object_vars($post));

            /*
            echo "<pre>";
            print_r($data);
            die();
             *
             */


            $view->setVariable('data', $data);


            //validate parent

            $pstat = $member->validateParent($post->upperId);

            if($pstat['code'] == 'F'){
                $conn->rollback();
                $view->setVariable('errmsg', $pstat['msg']);
                return $view;
            }


            // GENERATE New SN
            $snStorage = new \MLM\Model\Sn\Storage($db);
            $getPrefix = $snStorage->getSNConfig('SN_PREFIX');
            while($getPrefix->next()){
                    $res = $getPrefix->current();
                    $prefix = $res['str_value'];
            }


            $getLen = $snStorage->getSNConfig('SN_NUMBER_LENGTH');
            while($getLen->next()){
                    $res = $getLen->current();
                    $len = $res['int_value'];
            }


            $resSN = $snStorage->genSN($prefix, $len);
            $resArr = explode(",", $resSN);
            $memberCode = $resArr[0];
            $memberPIN = $post->pass;


            // assign data member
            $memberName = $post->firstName." ".$post->lastName;
            $member->name = $memberName;
            $member->parentId = $post->upperId;
            $member->sponsorId = $post->sponsorId;
            $member->matrik1Id = $post->upperId;
            $member->typeId = 2;
            $member->statusId = 1;
            $member->startDtm = $storage->now();
            $member->pos = $post->pos;


            $member->code = $memberCode;
            $member->pin = md5($memberPIN);

            $memberId = $member->save();

            if(!$memberId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            $member->id = $memberId;

            /*
             * Account
             */

            $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
            $acc = new \MLM\Model\Member\Account($accStorage);

            $acc->accNum = $member->code;
            $acc->accName = $member->name;
            $acc->memberId = $memberId;
            $acc->amount = 0;
            $acc->amount1 = 0;
            $acc->amount3 = 0;
            $acc->amount2 = 0;
            $acc->amount4 = 0;
            $acc->status = 'OK';


            $accId = $acc->save();

            if(!$accId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            // contact data
            /*
             * insert contact
             * insert member_contact
             */


            $cStorage = new \MLM\Model\Contact\Storage($this->_db);
            $contact = new \MLM\Model\Contact($cStorage);

            $contact->name = $memberName;
            $contact->ktp = $post->ktp;
            $contact->mobile = $post->mobile;
            $contact->address = $post->address;
            $contact->email = $post->email;
            $contact->city = $post->city;
            $contact->countryId = $post->country;

            $contactId = $contact->save();

            if(!$contactId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }

            $mcStorage = new \MLM\Model\Member\Contact\Storage($this->_db);
            $memberContact = new \MLM\Model\Member\Contact($mcStorage);

            $memberContact->memberId = $memberId;
            $memberContact->contactId = $contactId;
            $memberContact->typeId = 2;
            $memberContact->startDat = $mcStorage->now();

            $mcId = $memberContact->save();

            if(!$mcId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;

            }

            // update sn to acctive

            $snstatus = $storage->updateSn($member->code,3);

            $req = $member->createRequest();
            if(!$req){
                $conn->rollback();
                $view->setVariable('errmsg', 'Registration failed, please try again');
                return $view;
            }
            $conn->commit();


            $mailMsg = "<br><a href='fx-tradepoint.co.uk'>FX Trade Point</a><br><hr><br>
                        Dear ".$memberName.",<br>
                        We are very thankful for joining with us,you are now a valuable consumer of our FX Trade Point beautiful family. we wish you best of luck for your future earnings. Please check your login details:

                        <br><br><br>

                        Name : ".$memberName."<br><br>
                        Customer ID : ".$member->code."<br><br>
                        Password : ".$memberPIN."<br><br>

                        <br><br><br>

                        Regards,<br>
                        FX Trade Point<br>
                        <hr><br><br>
                        <center>
                        For more information email us to info@fx-tradepoint.co.uk<br>
                        www.fx-tradepoint.co.uk
                        </center>";

            $functModel->sendMail($post->email, $mailMsg);


            return $this->redirect()->toUrl('addmember?msg=Registration success');

        }

        $request = $this->getRequest();
        $getParams = $request->getQuery();

        $upid = $getParams["upid"];
        $pos = $getParams["pos"];

        $spId = $identity->member_id;
        $data["sponsorId"] = $spId;
        $data["sponsorCode"] = $identity->member_code;
        $data["sponsorName"] = $identity->member_name;

        if ($spId != ""){

            $upline = $storage->getMemberDetail($upid);
            while($upline->next()){
                    $res = $upline->current();

                    $data["upperId"] = $res["member_id"];
                    $data["upperCode"] = $res["member_code"];
                    $data["upperName"] = $res["member_name"];
                    $data["pos"] = $pos;

            }
        }




        $countryList = $functModel->countryList();

        $view->setVariable('countryList', $countryList);
        $view->setVariable('msg', $getParams["msg"]);
        $view->setVariable('data', $data);
        $view->setVariable('spId', $spId);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>My Team</li> <li class='active'>Add New Team </li>";

        return $view;
    }


    public function updateaccAction() {

        // seting layout

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        //$form = array();

        $identity = $this->hasSession();
        //print_r($identity);
        $data = array();

        $data['memberId'] = $identity->member_id;

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
                
        $view->setVariable('data', $data);
        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");

        $request = $this->getRequest();
        if ($request->isPost()) {
            
            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);

            $data = array_merge($data,  get_object_vars($post));
            //print_r($data);
            $view->setVariable('data', $data);
            // assign data member
      

            $dataAcc = array(
                'bank_id'  => $post->bank_id,
                'bank_acc_no'     => $post->bank_acc_no,
                'bank_acc_name'   => $post->bank_acc_name,
                'bank_city_name'   => $post->bank_city_name
            );

            $where = array('account_id' => $post->account_id);
            
            $accId = $accStorage->updateAccount($dataAcc, $where);
            
            if(!$accId){
                $conn->rollback();
                $view->setVariable('msg', 'Update account Gagal');
                return $view;
            }
            

            
            $conn->commit();

            return $this->redirect()->toUrl('profile');

        }

        $banks = $accStorage->getBankList();
        $accounts = $accStorage->getAccountBank($memberId);


        while ($accounts->next()) {
                $account = $accounts->current();
                
                $data['account_id'] = $account['account_id'];
                $data['account_num'] = $account['account_num'];
                $data['account_name'] = $account['account_name'];
                $data['account_status'] = $account['account_status'];
                $data['bank_id'] = $account['bank_id'];
                $data['bank_acc_no'] = $account['bank_acc_no'];
                $data['bank_acc_name'] = $account['bank_acc_name'];
                $data['bank_city_name'] = $account['bank_city_name'];
            
        }

        
        $view->setVariable('banks', $banks);
        $view->setVariable('dataAcc', $data);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Profile</li> <li class='active'>Edit Bank Account</li>";
        return $view;
    }



    public function updatecontactAction() {

        // seting layout

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        //$form = array();

        $identity = $this->hasSession();
        //print_r($identity);
        $data = array();

        $data['memberId'] = $identity->member_id;

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $conStorage = new \MLM\Model\Member\Contact\Storage($db);
        $functModel = new \MLM\Model\Functions;

        $view->setVariable('data', $data);
        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            });

            $('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
                    $(this).prev().focus();
            });
        })
        ");
        
        $script->appendScript('
          jQuery(function($) {
            $("textarea[class*=autosize]").autosize({append: "\n"});
        })
        ');

        $request = $this->getRequest();
        if ($request->isPost()) {

            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);

            $data = array_merge($data,  get_object_vars($post));
            
            $view->setVariable('data', $data);
            // assign data member

            $dataContact = array(
                'contact_name'      => $post->contact_name,
                'contact_phone'     => $post->contact_phone,
                'contact_mobile'    => $post->contact_mobile,
                'contact_email'     => $post->contact_email,
                'contact_address'   => $post->contact_address,
                'contact_city'      => $post->contact_city,
                'contact_province'  => $post->contact_province,
                'country_id'        => $post->country_id,
                'post_code'         => $post->post_code,
                'gender'            => $post->gender,
                'marital_status'    => $post->marital_status,
                'birth_dat'         => $post->birth_dat
            );

            $where = array('contact_id' => $post->contact_id);
            $conId = $conStorage->updateContact($dataContact, $where);

            if(!$conId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Edit Profile Failed.');

                $countryList = $functModel->countryList();
                $view->setVariable('countryList', $countryList);
                return $view;
            }


            if ($post->family_id != ""){

                $dataContact = array(
                    'contact_name'      => $post->family_name
                );

                $where = array('contact_id' => $post->family_id);
                $conId = $conStorage->updateContact($dataContact, $where);

                if(!$conId){
                    $conn->rollback();
                    $view->setVariable('errmsg', 'Edit Profile Failed..');

                    $countryList = $functModel->countryList();
                    $view->setVariable('countryList', $countryList);
                    return $view;
                }

            }else{

                /*
                 * insert contact
                 * insert member_contact
                 */
                $cStorage = new \MLM\Model\Contact\Storage($db);
                $contact = new \MLM\Model\Contact($cStorage);

                $contact->name = $post->family_name;
           
                $familyId = $contact->save();

                if(!$familyId){
                    $conn->rollback();
                    $view->setVariable('errmsg', 'Edit Profile Failed...');

                    $countryList = $functModel->countryList();
                    $view->setVariable('countryList', $countryList);
                    return $view;
                }

                $memberContact = new \MLM\Model\Member\Contact($conStorage);

                $memberContact->memberId = $memberId;
                $memberContact->contactId = $familyId;
                $memberContact->typeId = 4;
                $memberContact->startDat = $conStorage->now();

                $mcId = $memberContact->save();

                if(!$mcId){
                    $conn->rollback();
                    $view->setVariable('errmsg', 'Edit Profile Failed....');

                    $countryList = $functModel->countryList();
                    $view->setVariable('countryList', $countryList);

                    return $view;

                }

            }
            

            //Update Member Name
            $memStorage = new \MLM\Model\Member\Storage($db);

            $data = array(
                'member_name'  => $post->contact_name
            );


            $where = array('member_id' => $memberId);

            $res = $memStorage->updateMember($data, $where);

            if(!$res){
                $conn->rollback();
                $view->setVariable('errmsg', 'Edit Profile Failed.....');

                $countryList = $functModel->countryList();
                $view->setVariable('countryList', $countryList);

                return $view;
            }

            $conn->commit();

            return $this->redirect()->toUrl('profile');

        }

        
        //get Contact
        $contacts = $conStorage->getMemberContact($memberId);
        while ($contacts->next()) {
                $contact = $contacts->current();

                $data['contact_id'] = $contact['contact_id'];
                $data['contact_name'] = $contact['contact_name'];
                $data['contact_phone'] = $contact['contact_phone'];
                $data['contact_email'] = $contact['contact_email'];
                $data['contact_mobile'] = $contact['contact_mobile'];
                $data['contact_address'] = $contact['contact_address'];
                $data['contact_city'] = $contact['contact_city'];
                $data['contact_province'] = $contact['contact_province'];
                $data['country_id'] = $contact['country_id'];
                $data['post_code'] = $contact['post_code'];
                $data['birth_dat'] = $contact['birth_dat'];
                $data['gender'] = $contact['gender'];
                $data['marital_status'] = $contact['marital_status'];
        }

        //get Contact Family
        $contactsF = $conStorage->getMemberContactFamily($memberId);
        while ($contactsF->next()) {
                $contactF = $contactsF->current();

                $data['family_id'] = $contactF['contact_id'];
                $data['family_name'] = $contactF['contact_name'];
        }

        $countryList = $functModel->countryList();
        
        $view->setVariable('countryList', $countryList);
        $view->setVariable('banks', $banks);
        $view->setVariable('data', $data);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Profile</li> <li class='active'>Edit Profile</li>";
        return $view;
    }


    public function changepassAction() {
        $identity = $this->hasSession();
        // seting layout
        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $request = $this->getRequest();
        if ($request->isPost()) {
            
            $conn->beginTransaction();
            
            $post = $request->getPost();

            $oldPass = $post->oldPass;
            $newPass = $post->newPass;

            $storage = new \MLM\Model\Member\Storage($db);
            $memberDetail = $storage->getMemberDetail($memberId);
            while ($memberDetail->next()) {
                $md = $memberDetail->current();
                $CurrPin = $md['pin'];
            }

            //Check Old Pass
            if ($CurrPin != md5($oldPass)){
                $view->setVariable('errmsg', 'Current password is invalid');
                return $view;
            }

            
            $data = array(
                'pin'  => md5($newPass)
            );


            $where = array('member_id' => $memberId);

            $res = $storage->updateMember($data, $where);

            if(!$res){
                $conn->rollback();
                $view->setVariable('errmsg', 'Change Password Failed');
                return $view;
            }


            $conn->commit();

            return $this->redirect()->toUrl('profile');

        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Profile</li> <li class='active'>Change Password</li>";
        return $view;
    }

    public function changeavatarAction() {

        $identity = $this->hasSession();
        
        // seting layout
        if ($identity->member_type_id == 4) $this->layout('layout/admin');
        else $this->layout('layout/member');
        
        $view = new ViewModel();
        // init data and instance object

        

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
                          $('#id-input-file-1 , #id-input-file-2').ace_file_input({
                            no_file:'No File ...',
                            btn_choose:'Choose',
                            btn_change:'Change',
                            droppable:false,
                            onchange:null,
                            thumbnail:false //| true | large
                            //whitelist:'gif|png|jpg|jpeg'
                            //blacklist:'exe|php'
                            //onchange:''
                            //
                    });

                    $('#id-input-file-3').ace_file_input({
                            style:'well',
                            btn_choose:'Drop files here or click to choose',
                            btn_change:null,
                            no_icon:'icon-cloud-upload',
                            droppable:true,
                            thumbnail:'small'//large | fit
                            //,icon_remove:null//set null, to hide remove/reset button
                            /**,before_change:function(files, dropped) {
                                    //Check an example below
                                    //or examples/file-upload.html
                                    return true;
                            }*/
                            /**,before_remove : function() {
                                    return true;
                            }*/
                            ,
                            preview_error : function(filename, error_code) {
                                    //name of the file that failed
                                    //error_code values
                                    //1 = 'FILE_LOAD_FAILED',
                                    //2 = 'IMAGE_LOAD_FAILED',
                                    //3 = 'THUMBNAIL_FAILED'
                                    //alert(error_code);
                            }

                    }).on('change', function(){
                            //console.log($(this).data('ace_input_files'));
                            //console.log($(this).data('ace_input_method'));
                    });


                    //dynamically change allowed formats by changing before_change callback function
                    $('#id-file-format').removeAttr('checked').on('change', function() {
                            var before_change
                            var btn_choose
                            var no_icon
                            if(this.checked) {
                                    btn_choose = 'Drop images here or click to choose';
                                    no_icon = 'icon-picture';
                                    before_change = function(files, dropped) {
                                            var allowed_files = [];
                                            for(var i = 0 ; i < files.length; i++) {
                                                    var file = files[i];
                                                    if(typeof file === 'string') {
                                                            //IE8 and browsers that don't support File Object
                                                            if(! (/\.(jpe?g|png|gif|bmp)$/i).test(file) ) return false;
                                                    }
                                                    else {
                                                            var type = $.trim(file.type);
                                                            if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif|bmp)$/i).test(type) )
                                                                            || ( type.length == 0 && ! (/\.(jpe?g|png|gif|bmp)$/i).test(file.name) )//for android's default browser which gives an empty string for file.type
                                                                    ) continue;//not an image so don't keep this file
                                                    }

                                                    allowed_files.push(file);
                                            }
                                            if(allowed_files.length == 0) return false;

                                            return allowed_files;
                                    }
                            }
                            else {
                                    btn_choose = 'Drop files here or click to choose';
                                    no_icon = 'icon-cloud-upload';
                                    before_change = function(files, dropped) {
                                            return files;
                                    }
                            }
                            var file_input = $('#id-input-file-3');
                            file_input.ace_file_input('update_settings', {'before_change':before_change, 'btn_choose': btn_choose, 'no_icon':no_icon})
                            file_input.ace_file_input('reset_input');
                    });

                    /////////
                    $('#modal-form input[type=file]').ace_file_input({
                            style:'well',
                            btn_choose:'Drop files here or click to choose',
                            btn_change:null,
                            no_icon:'icon-cloud-upload',
                            droppable:true,
                            thumbnail:'large'
                    })
        ");
        
        $request = $this->getRequest();
        if ($request->isPost()) {

             $files =  $request->getFiles()->toArray();
             
             $httpadapter = new \Zend\File\Transfer\Adapter\Http();
             $filesize  = new \Zend\Validator\File\Size(array('min' => 1000 )); //1KB
             $extension = new \Zend\Validator\File\Extension(array('extension' => array('jpg','jpg','jpeg','gif','png')));
             $httpadapter->setValidators(array($filesize, $extension), $files['file2']['name']);
             if($httpadapter->isValid()) {

                 $httpadapter->setDestination('/var/www/qowwam.com/web-mlm-engine/public/img/profile');
                 //$adapter->setDestination(dirname(__DIR__).'/assets');
                 if($httpadapter->receive($files['file2']['name'])) {
                    $newfile = $httpadapter->getFileName();

                    $fileName = $files['file2']['name'];

                    /////////////////////

                    $conn->beginTransaction();
                    
                    $storage = new \MLM\Model\Member\Storage($db);
                    
                    $data = array(
                        'img_profile'  => $fileName
                    );


                    $where = array('member_id' => $memberId);

                    $res = $storage->updateMember($data, $where);

                    if(!$res){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Ganti Foto Profile Gagal');
                        return $view;
                    }


                    $conn->commit();


                 }

                 
             }else{

                $dataError = $httpadapter->getMessages();
                $error = "";
                foreach($dataError as $key=>$row)
                {
                    $error .= $row."<br>";
                }

                

                $view->setVariable('errmsg', 'File tidak valid: '. $error);
                return $view;

             }


            
            return $this->redirect()->toUrl('profile');

        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    public function agentAction(){
        $identity = $this->hasSession();

		$this->layout('layout/member');

        $view = new ViewModel();

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $storage = new \MLM\Model\Member\Storage($db);
        $member = new \MLM\Model\Member($storage);

        $memberId = $identity->member_id;

        //Cek apakah sudah terdaftar menjadi agen
        $isAgent = "";
        $memberDetail = $storage->getMemberDetail($memberId);
        while ($memberDetail->next()) {
            $md = $memberDetail->current();
            $isAgent = $md['member_reff_id'];            
        }


        $request = $this->getRequest();
        if ($request->isPost() && $isAgent == "") {
            //$post = $request->getPost();

            $storageContact = new \MLM\Model\Member\Contact\Storage($this->_db);
            $contact = $storageContact->getMemberContact($memberId);
            while ($contact->next()) {
                    $res = $contact->current();
                    $address = $res["contact_address"]." ".$res["contact_city"]." ".$res["contact_province"];
            }


            $conn->beginTransaction();

            $dataA = $storage->addAgent($memberId, $identity->member_code, $identity->member_name, $address);
            while($dataA->next()){
                    $res = $dataA->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if($code > 0){
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
                return $view;
            }


            /***** Pindah ke Approval Admin
            
            $snStorage = new \MLM\Model\Sn\Storage($this->_db);

            // GET SN PT
            $num = "";
            $sn = "";
            $stts = 2;
            $start = 0;
            $limit = 1;
            $search = "true";
            $searchField = "agent_id = 100";
            
            $snPT = $snStorage->getSN($num, $sn, $stts, $start, $limit, $search, $searchField);

            $agentSN = $snPT[1][0]["SN"];
            $agentPIN = $snPT[1][0]["PIN"];

            //Jika SN PT tidak tersedia
            if ($agentSN == ""){


                // GENERATE New SN

                $getPrefix = $snStorage->getSNConfig('SN_PREFIX');
                while($getPrefix->next()){
                        $res = $getPrefix->current();
                        $prefix = $res['str_value'];
                }


                $getLen = $snStorage->getSNConfig('SN_NUMBER_LENGTH');
                while($getLen->next()){
                        $res = $getLen->current();
                        $len = $res['int_value'];
                }


                $resSN = $snStorage->genSN($prefix, $len);
                $resArr = explode(",", $resSN);
                $agentSN = $resArr[0];
                $agentPIN = $resArr[1];

                

            }
            
            // assign data member
            $member->name = $identity->member_name;
            $member->code = $agentSN;
            $member->pin = md5($agentPIN);
            $member->parentId = $identity->parent_id;
            $member->sponsorId = $identity->sponsor_id;
            $member->matrik1Id = $identity->matrik1_id;
            $member->typeId = 3;
            $member->statusId = 1;
            $member->startDtm = $storage->now();
            

            $agentId = $member->save();
            
            if(!$agentId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Pendaftaran Agent Gagal');
                return $view;
            }


            $data = array(
                'member_reff_id'  => $agentId
            );

            $where = array('member_id' => $memberId);

            $res = $storage->updateMember($data, $where);

            if(!$res){
                $conn->rollback();
                $view->setVariable('errmsg', 'Pendaftaran Agent Gagal');
                return $view;
            }

            //Update status SN
            $datasn = array(
                'sn_status'  => 3
                //,'agent_id'  => $agentId
            );

            $wheresn = array('sn_code' => $agentSN);
            $snstatus = $snStorage->updateSn($datasn, $wheresn);

             * 
             */

            $conn->commit();

            $view->setVariable('msg', $msg);
            $view->setVariable('isAgent', 1);
      

        }else{

            if ($isAgent != "") $view->setVariable('errmsg', "Anda sudah terdaftar menjadi Agent");
            $view->setVariable('isAgent', $isAgent);
            
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return $view;

    }


    public function upgradeAction() {

        // seting layout

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        //$form = array();

        $identity = $this->hasSession();
        //print_r($identity);
        $data = array();

        $data['memberId'] = $identity->member_id;

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $storage = new \MLM\Model\Member\Storage($this->_db);

        $view->setVariable('data', $data);
        
        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);

        //GET JUMLAH SALDO E-Wallet
        $balance = $accStorage->getTotalBalance($identity->member_code);

        $EwalletBalance = 0;
        while ($balance->next()) {
                $res = $balance->current();
                $EwalletBalance = $res['amount'];
        }


        $request = $this->getRequest();
        if ($request->isPost()) {

            $conn->beginTransaction();
            $post = $request->getPost();
            //$form = array_merge($form, $post);

            $data = array_merge($data,  get_object_vars($post));
            //print_r($data);
            $view->setVariable('data', $data);
            // assign data member

            $amount = $post["amount"];
            $pkg = $post["package"];
            $plan = $post["plan"];
            $payment = $post["payment"];
            $passtrans = $post["passtrans"];
            $currency = $post["currency"];

            $errorMsg = "";
            
            
            //cek saldo E-wallet
            if ($payment == 1 && $amount > $EwalletBalance){
                $errorMsg .= "* Your E-Wallet Balance is ".$EwalletBalance."<br>";
            }

            if ($errorMsg == "") {


                $dataU = $storage->upgradeMember($identity->member_code, $memberId, $amount, $pkg, $plan, $payment, $passtrans, $currency);

                while($dataU->next()){
                        $res = $dataU->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('upgrade?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
                
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }

        }

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                    ->get('inlineScript');
            $script->appendScript("
                jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    });

                    $('[data-rel=popover]').popover({html:true});

                });
            ");

        $packages = $storage->getPackages("parent_member_type_id", "is", "null and member_type_id > 5");


        $functModel = new \MLM\Model\Functions;
        $currencys = $functModel->currencyList();
        $payments = $functModel->paymentNameList();

        $view->setVariable('packages', $packages);
        $view->setVariable('currencys', $currencys);
        $view->setVariable('payments', $payments);
        $view->setVariable('EwalletBalance', $EwalletBalance);
        $view->setVariable('data', $data);

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Profile</li> <li class='active'>Upgrade Member Status </li>";
        return $view;
    }

    public function storiesAction() {

        $identity = $this->hasSession();
        $this->layout('layout/member');


        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        $this->layout()->navMenu = "<li class='active'>Success Stories  </li>";

        return $view;
    }


    public function loginAction() {
        $messages = '';
        $this->layout('layout/member');
        $view = new ViewModel();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost();

            //$sm = $this->getServiceLocator();
            //$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');

         
            $authAdapter = new AuthAdapter($this->_db, 'members', // there is a method setTableName to do the same
                    'member_code', // there is a method setIdentityColumn to do the same
                    'pin', // there is a method setCredentialColumn to do the same
                    "MD5(?) AND status_id in (1,2) " // setCredentialTreatment(parametrized string) 'MD5(?)'
            );

            $authAdapter
                    ->setIdentity($post['username'])
                    ->setCredential($post['passwd'])
            ;

            $auth = new AuthenticationService();
            $result = $auth->authenticate($authAdapter);

            
            //print_r($result);
			
            switch ($result->getCode()) {
                case Result::FAILURE_IDENTITY_NOT_FOUND:
                    // do stuff for nonexistent identity
                    return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
                    //break;

                case Result::FAILURE_CREDENTIAL_INVALID:
                    // do stuff for invalid credential
                    return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
                    //break;

                case Result::SUCCESS:
                    $storage = $auth->getStorage();
                    $storage->write($authAdapter->getResultRowObject(
                                    null, 'pin'
                    ));
                    $time = 89600; // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
//						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session

                    if ($post['rememberme']) {
                        $sessionManager = new \Zend\Session\SessionManager();
                        $sessionManager->rememberMe($time);
                    }

                    //Update last_login
                    $memberStorage = new \MLM\Model\Member\Storage($this->_db);
                    $memberStorage->updateLastLogin($post['username']);


                    $identity = $auth->getIdentity();
					//print_r($identity);
                    //Jika ADMIN
                    if ($identity->member_type_id == 4){
						
                        return $this->redirect()->toRoute('admin', array('controller' => 'Index', 'action' => 'index'));

                    }else {
						
                        return $this->redirect()->toUrl('index');
                        
                    }

                default:
                    // do stuff for other failure
                    break;
            }

            foreach ($result->getMessages() as $message) {
                $messages .= "$message\n";
            }
        }
		
        //echo "MSG = " . $messages;
        //$view->setVariable(array('msg' => $messages));
        $view->setVariable('msg', $messages);
        $view->setTemplate("mlm/member/blank.phtml");
        return $view;
    }


    public function logoutAction() {
        $auth = new AuthenticationService();

        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
        }

        $auth->clearIdentity();
//		$auth->getStorage()->session->getManager()->forgetMe(); // no way to get the sessionmanager from storage
        $sessionManager = new \Zend\Session\SessionManager();
        $sessionManager->forgetMe();

        return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
    }


    //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){
        

        if ($memberId == 100) $memberId2 = $memberId;
        else{
            $identity = $this->hasSession();            
            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);
        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId2, $isAgent);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId2, $isAgent);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }
    
    private function hasSession() {
        $auth = new AuthenticationService();

        $identity = $auth->getIdentity();
		//print_r($identity);
        if (!$auth->hasIdentity()) {     
			//echo "gak ada session";
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }
	
	

}
